package org.feng.controller;

import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.feng.base.constant.RedisConstant;
import org.feng.base.entity.Result;
import org.feng.entity.Menu;
import org.feng.entity.User;
import org.feng.entity.req.LoginRequest;
import org.feng.entity.res.CaptchaImageResponse;
import org.feng.entity.res.LoginResponse;
import org.feng.entity.res.UserInfoResponse;
import org.feng.feign.MenuFeign;
import org.feng.feign.UserFeign;
import org.feng.utils.ResponseUtil;
import org.feng.utils.UUIDUtil;
import org.feng.utils.UserUtil;
import org.feng.utils.redis.RedisString;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author 冯帅
 * @des TODO
 * @date 2022/1/22 9:30
 * @email 15612509687@163.com
 */
@AllArgsConstructor
@RestController
@Slf4j
@RequestMapping("/auth")
@Api(tags = "认证权限接口")
public class AuthController {

    private final UserFeign userFeign;
    private final MenuFeign menuFeign;
    private final RedisString redisString;


    /**
     * 登录
     *
     * @param login
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<LoginResponse> login(@RequestBody @Validated LoginRequest login) {
        String vCode = (String) redisString.get(login.getKey());
        if (vCode == null) {
            return Result.error("验证码已失效");
        }
        if (!vCode.equalsIgnoreCase(login.getCode())) {
            return Result.error("请输入正确的验证码");
        }
        User user = ResponseUtil.checkResponse(userFeign.getUserByUserName(login.getUsername()));
        if (SaBase64Util.encode(login.getPassword()).equals(user.getPassword())) {
            StpUtil.login(user.getId());
            redisString.set(RedisConstant.USER_INFO_PREFIX + user.getId(), JSON.toJSONString(user));
            redisString.set(RedisConstant.USER_INFO_DEPT_ID_PREFIX + user.getId(), user.getDeptId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setToken(tokenInfo.tokenValue);
            loginResponse.setTokenName(tokenInfo.tokenName);
            return Result.success(loginResponse);
        } else {
            return Result.error("账号或密码错误");
        }
    }

    /**
     * 获取验证码
     *
     * @return
     */
    @ApiOperation("获取验证码")
    @GetMapping("/captchaImage")
    public Result<CaptchaImageResponse> captcha() throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha();
        String key = UUIDUtil.getUUID();
        CaptchaImageResponse response = CaptchaImageResponse
                .builder()
                .img(specCaptcha.toBase64())
                .key(key)
                .build();
        redisString.set(key, specCaptcha.text().toLowerCase(), 60000L);
        return Result.success(response);
    }

    /**
     * 获取按钮权限
     *
     * @return
     */
    @ApiOperation("获取按钮权限")
    @GetMapping("/getButtons")
    public Result<List<Menu>> getButtons() {
        User user = ResponseUtil.checkResponse(userFeign.getById(UserUtil.getUserId()));
        List<Menu> list = ResponseUtil.checkResponse(menuFeign.getButtons(user.getRoleId()));
        return Result.success(list);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public Result<UserInfoResponse> getUserInfo() {
        User user = ResponseUtil.checkResponse(userFeign.getById(UserUtil.getUserId()));
        if (Objects.isNull(user)) {
            return Result.error("用户不存在");
        }
        return Result.success(BeanUtil.toBean(user, UserInfoResponse.class));
    }
}
